package utils

import (
	"net/http"
	"net/url"
	"strings"
)

var defaultHeader = map[string]string{
	"Upgrade-Insecure-Requests": "1",
	"User-Agent":                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
	"Accept":                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
	"Accept-Encoding":           "gzip, deflate",
	"Accept-Language":           "zh-CN,zh;q=0.9",
	"Connection":                "keep-alive",
}

// 传入地址获取cookie
func (s *SessionManage) GetHeader(str string) map[string]string {
	host := ""
	if strings.HasPrefix(str, "http") {
		u, err := url.Parse(str)
		if err == nil {
			host = u.Host
		}
	} else {
		host = str
	}
	s.rwh.Lock()
	defer s.rwh.Unlock()
	header := s.HeaderMap[host]
	if header == nil {
		s.HeaderMap[host] = defaultHeader
		return defaultHeader
	}
	return header
}
func (s *SessionManage) GetHttpHeader(str string) http.Header {
	host := ""
	if strings.HasPrefix(str, "http") {
		u, err := url.Parse(str)
		if err == nil {
			host = u.Host
		}
	} else {
		host = str
	}
	s.rwh.Lock()
	defer s.rwh.Unlock()
	header := s.HeaderMap[host]
	if header == nil {
		s.HeaderMap[host] = defaultHeader
		header = defaultHeader
	}
	headers := map[string][]string{}
	for k, v := range header {
		headers[k] = []string{v}
	}
	cookie := s.GetCookiesString(str)
	if cookie != "" {
		headers["cookie"] = []string{cookie}
	}
	return headers
}

// 传入地址 更新cookie
func (s *SessionManage) SetHeader(str string, key, value string) {
	host := ""
	u, err := url.Parse(str)
	if err == nil {
		host = u.Host
	}
	s.rwh.Lock()
	defer s.rwh.Unlock()
	oldHeaderMap := s.HeaderMap[host]
	if oldHeaderMap == nil {
		oldHeaderMap = defaultHeader
	}
	oldHeaderMap[key] = value
	s.HeaderMap[host] = oldHeaderMap
	return
}
